const Service = require('egg').Service;

class ScoreService extends Service {
  // 添加学生的成绩数据
  async add() {
    // 这个插入数据，必须选取已经存在的学生，
    const { ctx } = this;
    const { name, stuId, theory, skill } = ctx.request.body;
    const sql = `insert into score (name, stuId, theory, skill) 
    values ('${name}','${stuId}', '${theory}', '${skill}');`
    const data = await ctx.app.mysql.query(sql)
    if (data.insertId) {
      return await { id: data.insertId, code: 0, msg: 'success' };
    } else {
      return await { code: -1, msg: 'fail' };
    }
  }

  // 更新学生数据接口
  async update() {
    // 根据学号，找到这个学生，然后更改成绩 理论成绩 还是技能成绩
    const { stuId, theory, skill } = this.ctx.request.body;
    const sql = `update score set theory=${theory}, skill=${skill} where stuId = ${stuId};`
    const data = await this.ctx.app.mysql.query(sql);
    return await data;
  }

  // 删除学生成绩数据
  async delete() {
    const { stuId } = this.ctx.params;
    const sql = `delete from score where stuId=${stuId};`
    const data = await this.ctx.app.mysql.query(sql);
    if (data.affectedRows) {
      return await {
        msg: '删除成功',
        affectedRows: data.affectedRows,
        code: 0
      };
    } else {
      return await {
        msg: '删除失败',
        code: -1
      };
    }
  }

  // 根据条件搜索学生数据 name 理论 或者 技能
  async search() {
    const { name, theory, skill } = this.ctx.query;
    console.log('theory: ', theory)
    console.log('skill: ', skill)
    let sql = '';
    if (theory === '理论') {
      sql = `select id, name, theory from score where name='${name}';`
    } else if (skill === '技能') {
      sql = `select id, name, skill from score where name='${name}';`
    }
    console.log('sql:----', sql)
    const data = await this.ctx.app.mysql.query(sql)
    return await data;
  }

  // 分页接口
  async page() {
    // console.log('page:--------------------------')
    // 这个是对score表操作 分页 操作
    const { ctx } = this;
    // totalCount
    const totalSql = `select count(name) as num from score;`;
    const total = await ctx.app.mysql.query(totalSql);
    const totalCount = total[0].num;
    const { page = 0, size } = ctx.query;
    const sql = `select * from score limit ${size} offset ${page * size};`
    const data = await ctx.app.mysql.query(sql);
    return await { data, totalCount }
  }

  async findGrade() {
    const sql = `select * from grade`;
    const data = await this.ctx.app.mysql.query(sql);
    data.forEach((item) => {
      item.time = this.ctx.helper.getTimer(item.time)
    })
    return data;
  }
}

module.exports = ScoreService
